<script setup lang="ts">
import {ref} from "vue";


const props = withDefaults(defineProps<{
  label?: string,
  requiredIcon?: boolean,
  getDate?: Function
}>(), {
  label: '',
  requiredIcon: true,
  getDate: () => {
  }
})

/**
 * 日期相关参数
 */
const date = ref(null)
const formatDateValue = ref('')

/**
 * 格式化日期
 * @param date
 */
function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以加1
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/**
 * 日期选择器值变化事件
 * @param date
 * @param isActive
 */
function dateValueUpdateAction(date: any, isActive: any) {
  isActive.value = false
  formatDateValue.value = formatDate(date)
  // 将值传到父组件绑定的属性
  props.getDate(formatDateValue.value)
}

</script>

<template>
  <v-row align="center">
    <v-col>
      <v-dialog max-width="500">
        <template v-slot:activator="{ props: activatorProps }">
          <v-text-field
            v-model="formatDateValue"
            v-bind="activatorProps"
            :label="label"
            variant="outlined"
            :prepend-icon="requiredIcon ? 'mdi-asterisk' : ''"
            readonly=""
            clearable
          >
          </v-text-field>
        </template>

        <template v-slot:default="{ isActive }">
          <v-date-picker v-model="date" hide-header view-mode="year"
                         @update:modelValue="()=>dateValueUpdateAction(date,isActive)">
          </v-date-picker>
        </template>
      </v-dialog>
    </v-col>
  </v-row>
</template>

<style scoped>

</style>
